package com.starview.star.code;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import com.starview.platform.data.value.ResourceURI;
import com.starview.platform.resource.ResourceException;
import com.starview.platform.resource.Resources;
import com.starview.star.code.repository.CodeParser;
import com.starview.star.code.repository.CodeTree;
import com.starview.star.compiler.ErrorReport;

public class CafeClassParser implements CodeParser
{
  @Override
  public String getExtension()
  {
    return CafeCode.EXTENSION;
  }

  @Override
  public CodeTree parse(ResourceURI uri, ErrorReport errors) throws ResourceException
  {
    InputStream stream = Resources.getInputStream(uri);

    if (stream != null)
      return parse(uri, stream, errors);
    return null;
  }

  @Override
  public CodeTree parse(ResourceURI uri, InputStream stream, ErrorReport errors) throws ResourceException
  {
    try {
      byte[] codeArray = new byte[stream.available()];
      byte[] buffer = new byte[codeArray.length];
      int pos = 0;
      int read;

      do {
        read = stream.read(buffer);
        if (read >= 0) {
          if (pos + read > codeArray.length)
            codeArray = Arrays.copyOf(codeArray, codeArray.length + read);

          for (int ix = 0; ix < read; ix++)
            codeArray[pos++] = buffer[ix];
        }
      } while (read >= 0);
      if (pos < codeArray.length) // trim the code buffer
        codeArray = Arrays.copyOf(codeArray, pos);

      return new CafeCode(uri.getPath(), codeArray);

    } catch (IOException e) {
      throw new ResourceException("could not access resource", e);
    } finally {
      try {
        stream.close();
      } catch (IOException e) {
      }
    }
  }

}
